<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License, version 2, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * @category  PayIntelligent
 * @package   PayIntelligent_ClickandBuy
 * @copyright (C) 2010 PayIntelligent GmbH  <http://www.payintelligent.de/>
 * @license   GPLv2
 */

class pi_clickandbuy_recurring {
	var $code;
	var $title;
	var $public_title;
	var $description;
	var $enabled;
	var $_check;
	var $secret_key;
	var $amount;
	var $db;
	
	function __construct() {
		global $order;
		$this->code = 'pi_clickandbuy_recurring';
		$this->title = MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_UPA_TEXT;
		$this->public_title = MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_TEXT_TITLE;
		$this->description = utf8_decode ( MODULE_PAYMENT_PI_CLICKANDBUY_TEXT_DESCRIPTION );
		$this->sort_order = MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_SORT_ORDER;
		$this->enabled = ((MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_STATUS == 'True') ? true : false);
		$this->secret_key = MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_SECRET_KEY;
		$this->db = $db;
		
		if ((int)MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_ORDER_STATUS_ID > 0)
			$this->order_status = MODULE_PAYMENT_RECURRING_CLICKANDBUY_ORDER_STATUS_ID;
		
		$this->check();
		if (is_object($order))
			$this->update_status();
	}
	
	function get_info_destination($customer_country_code) {
		$info_destination = "GB_en";
		
		switch ($customer_country_code) {
			case "AT" :
				$info_destination = "AT_de";
				break;
			case "US" :
				$info_destination = "US_en";
				break;
			case "DE" :
				$info_destination = "DE_de";
				break;
			case "GB" :
				$info_destination = "GB_en";
				break;
			case "ES" :
				$info_destination = "ES_es";
				break;
			case "FR" :
				$info_destination = "FR_fr";
				break;
			case "NL" :
				$info_destination = "NL_nl";
				break;
			case "IT" :
				$info_destination = "IT_it";
				break;
			case "DK" :
				$info_destination = "DK_da";
				break;
			case "NO" :
				$info_destination = "NO_no";
				break;
			case "FI" :
				$info_destination = "FI_fi";
				break;
			case "SE" :
				$info_destination = "SE_sv";
				break;
			case "PT" :
				$info_destination = "PT_pt";
				break;
		}
		return $info_destination;
	}
	
	function update_status() {
		global $order;
		
		if (($this->enabled == true) && (( int ) MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_ZONE > 0)) {
			$check_flag = false;
			$check = $this->db->db_query("SELECT zone_id FROM ".TABLE_ZONES_TO_GEO_ZONES." WHERE geo_zone_id = '".MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_ZONE."' AND zone_country_id = '".$order->billing ['country'] ['id']."' ORDER BY zone_id");
			
			while(!$check->EOF) {
				if ($check ['zone_id'] < 1) {
					$check_flag = true;
					break;
				} elseif ($check ['zone_id'] == $order->billing ['zone_id']) {
					$check_flag = true;
					break;
				}
				$check->MoveNext();
			}
			
			if ($check_flag == false)
				$this->enabled = false;
		}
	}
	
	function javascript_validation() {
		return false;
	}
	
	function selection() {
		global $order;
		
		$customer_country = $order->customer['country'] ['iso_code_2'];
		$info_destination = $this->get_info_destination($customer_country);
		
		return array('id' => $this->code, 
					'module' => $this->public_title, 
					'description' => image('images/payments/pi_clickandbuy_logo.png').'<br />'.MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_CHECKOUT_TEXT_INFO.'<br /><b><small>(<a href="http://clickandbuy.com/'.$info_destination.'/info.html" target="_blank" >'.MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_CHECKOUT_MORE_INFO_LINK_TITLE.'</a>)</small></b>' );
	}
	
	function pre_confirmation_check() {
		return false;
	}
	
	function confirmation() {
		return false;
	}
	
	function process_button() {
		return false;
	}
	
	function before_process() {
		global $order, $cab;
		
		if(isset($_GET['checkout']) && $_GET['checkout'] == 'success')
			return;
		else {
			$call_url = $cab->doTrans();
			redirect($call_url);
			return;
		}
	}
	
	function after_process() {
		global $insert_id;
		$external_id = $_GET ['externalID'];
		
		$this->db->db_query("UPDATE 
								".DB_PREFIX."picab_orders 
							SET 
								handshake = '1',
								shopOrderID = '".$insert_id."',
								modified = '".date( "Y-m-d H:i:s" )."' 
							WHERE 
								externalID = '".$external_id."'" );
								
		$this->db->db_query("UPDATE 
									".TABLE_ORDERS." 
								SET 
									orders_status = '".MODULE_PAYMENT_PI_CLICKANDBUY_ORDER_STATUS_ID."' 
								WHERE 
									orders_id = '".$insert_id."' ");
									
		$this->db->db_query("INSERT INTO
								orders_status_history 
								".TABLE_ORDERS_STATUS_HISTORY."
								(orders_id, orders_status_id, date_added, customer_notified)
							VALUES
								('".$insert_id."',
								'".MODULE_PAYMENT_PI_CLICKANDBUY_ORDER_STATUS_ID."',
								NOW(),
								'0'");
		return false;
	}
	
	function get_error() {
		return false;
	}
	
	function check() {
		global $db;
		if(!isset($this->_check)) {
			$check = $db->db_query("SELECT configuration_value from ".TABLE_CONFIGURATION." WHERE configuration_key = 'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_STATUS'");
			$this->_check = $check->_numOfRows;
		}
		return $this->_check;
	}
	
	function install() {
		
		$check = $this->db->db_query("SHOW TABLES LIKE '".DB_PREFIX."picab_mms'");
		if($check->_numOfRows == 0) {
			$this->db->db_query("CREATE TABLE picab_mms (
			  eventID varchar(64) NOT NULL,
			  shopOrderID varchar(64) NOT NULL,
			  externalID varchar(64) NOT NULL,
			  transactionID varchar(64) NOT NULL,
			  oldState varchar(64) NOT NULL,
			  newState varchar(64) NOT NULL,
			  xml text NOT NULL,
			  created timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP)");
		}
		
		$check = $this->db->db_query("SHOW TABLES LIKE '".DB_PREFIX."picab_orders'");
		if($check->_numOfRows == 0) {
			$this->db->db_query("CREATE TABLE picab_orders (
			  id int(11) NOT NULL auto_increment,
			  shopOrderID varchar(32) NOT NULL,
			  shopUserID varchar(32) NOT NULL,
			  transactionID varchar(64) NOT NULL,
			  externalID varchar(64) NOT NULL,
			  paymentType varchar(32) NOT NULL,
			  authorization tinyint(1) NOT NULL,
			  authorizationID varchar(64) NOT NULL,
			  handshake tinyint(1) NOT NULL,
			  closed tinyint(1) NOT NULL,
			  recAmount decimal(9,2) NOT NULL,
			  amount decimal(9,2) NOT NULL default '0.00',
			  debited decimal(9,2) NOT NULL,
			  refunded decimal(9,2) NOT NULL default '0.00',
			  cancelled decimal(9,2) NOT NULL default '0.00',
			  currency varchar(4) NOT NULL,
			  created datetime NOT NULL,
			  modified datetime NOT NULL,
			  PRIMARY KEY (`id`),
			  KEY `orders_id` (`shopOrderID`))");
		}
		
		$check = $this->db->db_query("SHOW TABLES LIKE '".DB_PREFIX."picab_transactions'");
		if($check->_numOfRows == 0) {
			$this->db->db_query("CREATE TABLE picab_transactions (
			  id int(11) NOT NULL auto_increment,
			  shopOrderID varchar(64) NOT NULL,
			  transactionID varchar(64) NOT NULL,
			  externalID varchar(64) NOT NULL,
			  transactionType varchar(64) NOT NULL,
			  description text NOT NULL,
			  amount decimal(9,2) NOT NULL default '0.00',
			  currency varchar(4) NOT NULL,
			  paid tinyint(1) NOT NULL,
			  status varchar(64) NOT NULL,
			  created datetime NOT NULL,
			  modified datetime NOT NULL,
			  PRIMARY KEY (`id`))");
		}
		
		$this->db->db_query( "INSERT INTO  ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_STATUS', 'True', '6', '1', 'cfg_select_option(array(\'True\', \'False\'), ', now())" );
		$this->db->db_query( "INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_MERCHANT_ID', '', '6', '3', NOW())" );
		$this->db->db_query( "INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_PROJECT_ID', '', '6', '3', NOW())" );
		$this->db->db_query( "INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_SECRET_KEY', '', '6', '3', NOW())" );
		$this->db->db_query( "INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_SECRET_KEY_MMS', '', '6', '3', NOW())" );		
		$this->db->db_query( "INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_DESCRIPTION', 'Billing Agreement', '6', '3', NOW())" );
		$this->db->db_query( "INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_NUMBER_LIMIT', '', '6', '3', NOW())" );
		$this->db->db_query( "INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_AMOUNT', '', '6', '3', NOW())" );
		$this->db->db_query( "INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_CURRENCY', '', '6', '3', NOW())" );
		$this->db->db_query( "INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_DATE_LIMIT', '', '6', '3', NOW())" );		
		$this->db->db_query( "INSERT INTO  ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_REVOKABLE', 'False', '6', '6', 'cfg_select_option(array(\'True\',\'False\'),', NOW())" );
		$this->db->db_query( "INSERT INTO  ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_INITIAL_AMOUNT', 'False', '6', '6', 'cfg_select_option(array(\'True\',\'False\'),', NOW())" );
		$this->db->db_query( "INSERT INTO  ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_SPECIAL_CASE', 'None', '6', '6', 'cfg_select_option(array(\'None\',\'Fast Checkout\',\'Partial Delivery\'),', NOW())" );		
		$this->db->db_query( "INSERT INTO  ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_SORT_ORDER', '0', '6', '0', now())" );
		$this->db->db_query( "INSERT INTO  ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, use_function, set_function, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_ZONE', '0', '6', '2', 'get_zone_class_title', 'cfg_pull_down_zone_classes(', now())" );
		$this->db->db_query( "INSERT INTO  ".TABLE_CONFIGURATION." (configuration_key, configuration_value, sort_order, use_function, set_function, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_ORDER_STATUS_ID', '6', '0', 'get_order_status_name', 'cfg_pull_down_order_statuses(', NOW())" );
		$this->db->db_query( "INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) VALUES ('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_ALLOWED', '', '6', '0', now())" );
	}
	
	function remove() {
		$this->db->db_query("DELETE FROM ".TABLE_CONFIGURATION." WHERE configuration_key IN ('".implode ( "', '", $this->keys () )."')" );
	}
	
	function keys() {
		return array (
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_STATUS', 
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_MERCHANT_ID', 
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_PROJECT_ID', 
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_SECRET_KEY', 
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_SECRET_KEY_MMS', 
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_DESCRIPTION', 
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_NUMBER_LIMIT', 
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_AMOUNT', 
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_CURRENCY', 
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_DATE_LIMIT', 
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_REVOKABLE', 
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_INITIAL_AMOUNT',
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_SPECIAL_CASE',    
	      	'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_SORT_ORDER',
	      	'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_ALLOWED',
			'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_ZONE',
	      	'MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_ORDER_STATUS_ID'
	    );    
	}
	
	function generate_shash($amount,$currency,$externalID,$additional_1 = '', $additional_2 = ''){
		$shash = md5($amount.$currency.$externalID.$this->secret_key.$additional_1.$additional_2);
		return $shash;		
	}
}
?>